package com.earnings.okhttputils.utils.ui.activity.common;

import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.earnings.R;
import com.earnings.okhttputils.utils.OkHttp.OkHttpUtils;
import com.earnings.okhttputils.utils.OkHttp.utils.ToastUtils;
import com.earnings.okhttputils.utils.UrlConstant.Constant;
import com.earnings.okhttputils.utils.UrlConstant.HttpUrl;
import com.earnings.okhttputils.utils.User;
import com.earnings.okhttputils.utils.god.GodLeftHandBaseActivity;
import com.earnings.okhttputils.utils.https.HttpMap;
import com.earnings.okhttputils.utils.https.HttpObjectCallback;

import com.earnings.okhttputils.utils.utils.CommonUtil;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/*
检查验证码
 */
public abstract class CodeCheckActivity extends GodLeftHandBaseActivity {


    private TextView phone,info;//
    private long secand=60;
    private final long time=60;
    private Button sumbit;//下一步


    @Override
    protected int onCreateLayoutId() {
        return R.layout.activity_code_check;
    }

    @Override
    protected void init() {
        setTitle("输入验证码");
        initCodeEdittext();
        phone= (TextView) findViewById(R.id.phone);
        info= (TextView) findViewById(R.id.info);
        phone.setText( bundleData.getString( "phone" ) );

        checkCodeSecand();
    }


/*
初始化验证码监听
 */
public void initCodeEdittext(){
    final Map<Integer,EditText> codeMap=new HashMap<>();
    for (int i = 1; i <=4 ; i++) {
        int rid=getIdFromXML( "code"+ i);
        final EditText code= (EditText) findViewById(rid);
        final int num=i;
        if(num==1){
            code.clearFocus();
            code.setFocusable(true);
            code.setFocusableInTouchMode(true);
            code.requestFocus();
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        }
       //code.setEnabled(false);
        codeMap.put(i,code);
        //监听输入
        code.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

                if(code.getText().toString().length()==1&&num!=4) {


                    code.clearFocus();
                    code.setBackgroundResource(R.drawable.code_radius_false);
                    EditText nowEditText= codeMap.get(num + 1);

                    nowEditText.setText("");
                    nowEditText.setFocusable(true);
                    nowEditText.requestFocus();
                    nowEditText.setBackgroundResource(R.drawable.code_radius_true);
                }else if(num==4&&code.getText().toString().length()!=0){
                    checkcode();
                }
            }
        });
        //监听删除
        code.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_DEL
                        && event.getAction() == KeyEvent.ACTION_DOWN) {

                    if(num!=1) {

                        EditText nowEditText= codeMap.get(num -1);
                        code.clearFocus();
                        code.setBackgroundResource(R.drawable.code_radius_false);
                        if(code.getText().toString().length()==0) nowEditText.setText("");
                        nowEditText.setFocusable(true);
                        nowEditText.requestFocus();
                        nowEditText.setBackgroundResource(R.drawable.code_radius_true);
                    }
                    code.setText("");
                    return true;
                }else{
                   // code.setText(event.getNumber());
                }
                return false;
            }
        });
        //重新获取焦点
        code.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus){
                    for (int j = 1; j < 4; j++) {
                        if(j!=num){
                        codeMap.get(j).setBackgroundResource(R.drawable.code_radius_false);
                        }else {
                        code.setBackgroundResource(R.drawable.code_radius_true);
                        }
                    }

                }
            }
        });
    }
}


public void checkcode(){
        String code="";
        for (int i = 1; i <=4 ; i++) {
            int rid=getIdFromXML( "code"+ i);
            EditText etcode= (EditText) findViewById(rid);
            code+=etcode.getText().toString();
        }
        checkcodeData( code );

        // public  void resultskip();
    }
    public void clearcode(){
        String code="";
        for (int i = 1; i <=4 ; i++) {
            int rid=getIdFromXML( "code"+ i);
            EditText etcode= (EditText) findViewById(rid);
            etcode.setText( "" );
            etcode.clearFocus();
            etcode.setBackgroundResource(R.drawable.code_radius_false);
            if(i==1) {
                etcode.setFocusable(true);
            etcode.requestFocus();
            etcode.setBackgroundResource(R.drawable.code_radius_true);}
        }


        // public  void resultskip();
    }
public abstract void checkCode(int type,String code);
    /*
         发送验证码
           */
    public void sendcode(){
      //  ToastUtils.showToast(getContext(),  bundleData.getString( "sessons","" )  );
        Map map= new HttpMap(getContext());
        map.put("mobile",phone.getText().toString());
        map.put("scene", bundleData.getInt( "type" )+"");
        map.put("type","mobile");
        if(bundleData.getInt( "type" )==Constant.SEND_CODE_TYPE_RESGISTER)
            map.put( "verify_code", bundleData.getString( "code" ) );

            OkHttpUtils.post().addHeader( "cookie", bundleData.getString( "sessons","" ) ).url( HttpUrl.SEND_CODE ).params(map ).build().execute( new HttpObjectCallback<String>( getContext() ) {

                @Override
                public void onSuccess(String object, String msg) {
                    ToastUtils.showToast(getContext(), msg );

                    saveNowSecand();
                    reSendSecend();
                }

                @Override
                    public void onFail(int code, String msg) {
                    ToastUtils.showToast(getContext(), msg );
                    finish();
                }

            } );

    }
    /*
       检验验证码
         */
    public void checkcodeData(final String code){
        Map map= new HttpMap(getContext());
        map.put("mobile",phone.getText().toString());
        map.put("code",code);/*
        if(bundleData.getInt( "type" )==Constant.SEND_CODE_TYPE_RESGISTER)
            map.put( "verify_code", bundleData.getInt( "code" ) );*/

        OkHttpUtils.post().url( HttpUrl.SEND_CODE_CHECK ).params(map ).build().execute( new HttpObjectCallback<String>( getContext() ) {

            @Override
            public void onSuccess(String object, String msg) {

                int type=bundleData.getInt("type");
                checkCode(type,code);
                finish();
            }

            @Override
            public void onFail(int code, String msg) {
                ToastUtils.showToast(getContext(), msg );
                clearcode();
            }

        } );

    }

    public void checkCodeSecand(){
        long nowtime=new Date().getTime();
        long now=(nowtime-CommonUtil.getUser().getCodesecand())/1000;
        if(now<time){
            secand=time-now;
            Log.e( Constant.TAG, now+" "+secand);
            reSendSecend();
        }else{

            sendcode();
        }
    }
    public void reSendSecend(){
        new Thread(new Runnable() {

            @Override
            public void run() {
                while (secand>0) {
                    try {
                        Message msg=new Message();
                        msg.what=1;
                        mhandler.sendMessage( msg );
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        Thread.currentThread().interrupt();
                    }

                }

            }
        }).start();
    }

    Handler mhandler=new Handler( new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            secand--;
            info.setTextColor( getResources().getColor( R.color.textmiddle ) );
            info.setText( "重新发送验证码("+secand+")" );
            info.setOnClickListener( null );
            if(secand==0){
                info.setText( "重新发送验证码" );
                info.setTextColor( getResources().getColor( R.color.style ) );
                info.setOnClickListener( new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        sendcode();
                        clearcode();
                    }
                } );
            }
            return false;
        }
    } );

    public void saveNowSecand(){
        secand=60;
       User user= CommonUtil.getUser();
        user.setCodesecand( new Date( ).getTime() );
        CommonUtil.commitUser( user );
    }
}
